package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/8/1 10:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    //  注入服务层对象
    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/findAll")
    public Result findAll(){
        //  调用服务层方法
        List<SeckillGoods> seckillGoodsList = seckillGoodsService.findAll();
        return Result.ok(seckillGoodsList);
    }

    //  获取秒杀详情信息.
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){
        //  调用服务层方法
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        return Result.ok(seckillGoods);
    }

    /**
     * 生成抢购码
     * @param skuId
     * @param request
     * @return
     */
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  先获取秒杀对象
        SeckillGoods seckillGoods = this.seckillGoodsService.getSeckillGoods(skuId);
        if (null != seckillGoods){
            //  获取当前系统时间
            Date currentTime = new Date();
            //  在秒杀开始之后，结束之前.
            if (DateUtil.dateCompare(seckillGoods.getStartTime(),currentTime) &&
            DateUtil.dateCompare(currentTime,seckillGoods.getEndTime())){
                //  生成抢购码. 对userId 进行md5 加密操作.
                String skuIdStr = MD5.encrypt(userId);
                return Result.ok(skuIdStr);
            }
        }
        //  默认返回
        return Result.fail().message("生成抢购码失败.");
    }

    //    http://api.gmall.com/api/activity/seckill/auth/seckillOrder/25?skuIdStr=c81e728d9d4c2f636f067f89cc14862

    /**
     * 预下单控制器.
     * @param skuId
     * @return
     */
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  校验抢购码： 页面传递：skuIdStr=c81e728d9d4c2f636f067f89cc14862 --> 后台再userId生成一个抢购码！
        String userId = AuthContextHolder.getUserId(request);
        String skuIdStr = request.getParameter("skuIdStr");
        //  调用服务层方法。
        return this.seckillGoodsService.seckillOrder(skuId,userId,skuIdStr);
    }

    /**
     * 检查秒杀状态。
     * @param skuId
     * @param request
     * @return
     */
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法
        return this.seckillGoodsService.checkOrder(skuId,userId);
    }

    /**
     * 秒杀结算页控制器
     * @param request
     * @return
     */
    @GetMapping("/auth/trade")
    public Result<Map> authTrade(HttpServletRequest request){
        //  获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //  调用服务层方法并返回.
        return Result.ok(seckillGoodsService.authTrade(userId));
    }

    /**
     * 秒杀提交订单.
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        //  在保存之前，需要给订单对象赋值一个userId
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //  调用服务层方法. 在订单微服务中已经有一个保存订单的实现类. 所以我们可以直接调用即可！
        Long orderId = this.orderFeignClient.submitOrder(orderInfo);
        if (null == orderId){
            return Result.fail().message("保存订单失败");
        }
        //  删除预下单数据，做真正保存订单数据.
        //  this.redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS,userRecode.getUserId(),orderRecode);
        this.redisTemplate.opsForHash().delete(RedisConst.SECKILL_ORDERS,userId);
        //  key = seckill:orders:users field=userId value=orderId
        this.redisTemplate.opsForHash().put(RedisConst.SECKILL_ORDERS_USERS,userId,orderId.toString());
        //  返回数据
        return Result.ok(orderId);
    }
}
